from odoo import fields, models


class SProductLock(models.Model):
    _name = 's.product.lock'
    _description = 'Product Lock'

    origin_product_id = fields.Many2one('product.product', 'origin Product')
    product_id = fields.Many2one('product.product', 'Product', index=True)
    qty = fields.Float('Qty', digits='Product Unit of Measure', copy=False)
    uom_id = fields.Many2one('uom.uom', string='Uom')
    lock_type = fields.Selection([('stock', 'Stock'), ('prepare', 'Prepare')], readonly=True)
    active = fields.Boolean('Active', default=True)

    lock_date = fields.Datetime('lock date', readonly=True, copy=False, default=fields.Datetime.now)

    sale_order_line_id = fields.Many2one('sale.order.line', string='Sale Order Line', readonly=True, copy=False)
    sale_id = fields.Many2one('sale.order', string='Sale Order', readonly=True, copy=False, index=True)
    commitment_date = fields.Datetime('commitment date', readonly=True, related='sale_id.commitment_date')

    order_qty = fields.Integer('order qty', compute='compute_order_qty')
    prepare_qty = fields.Integer(string='Prepare Quantity', readonly=True)

    purchase_id = fields.Many2one('purchase.order', string='purchase order', readonly=True, copy=False, index=True)
    purchase_line_id = fields.Many2one('purchase.order.line', string='purchase order line', readonly=True, copy=False)

    user_id = fields.Many2one('res.users', string='user', readonly=True, copy=False, default=lambda self: self.env.user)

    cancel = fields.Boolean('cancel', default=False, readonly=True, copy=False, index=True)

    scrap_rate = fields.Float(string='Scrap Rate', readonly=True)

    x_delete = fields.Boolean('Delete', default=False, readonly=True, copy=False, index=True)

    preparation_type = fields.Selection([
        ('bom', 'BOM'),
        ('presets', 'presets')
    ], readonly=True, copy=False)

    def compute_order_qty(self):
        for rec in self:
            if rec.sale_order_line_id:
                rec.order_qty = rec.sale_order_line_id.product_uom_qty
            elif rec.forecast_order_line_id:
                rec.order_qty = rec.forecast_order_line_id.market_forecast_quantity
            else:
                rec.order_qty = 0

    def action_unlock(self):
        self.write({'cancel': True})
        self.action_archive()